package com.sort;

public class Test_1 {
    public static void main(String[] args) {
        int arr[]=new int[1000000];
        for(int i=0;i<arr.length;i++){
            arr[i]= (int) (Math.random()*10000+1);
        }
        long s1=System.currentTimeMillis();
        A.quicksort(arr,0,arr.length-1);
        long e1=System.currentTimeMillis();
        System.out.println(e1-s1);

        for(int i=0;i<arr.length;i++){
            arr[i]= (int) (Math.random()*10000+1);
        }
        long s2=System.currentTimeMillis();
        A.mergesort(arr,0,arr.length-1);
        long e2=System.currentTimeMillis();
        System.out.println(e2-s2);
    }

}

class A{
    public static void quicksort(int[]arr,int left,int right){
        if(left>=right){
            return;
        }
        int par=partiton(arr,left,right);
        quicksort(arr,left,par-1);
        quicksort(arr,par+1,right);
    }
    public static int partiton(int[]arr,int start,int end){
        int i=start;
        int pivot=arr[start];
        while(start<end){
            while (start<end&&arr[end]>=pivot){
                end--;
            }
            while(start<end&&arr[start]<=pivot){
                start++;
            }
            swap(arr,start,end);
        }
        swap(arr,start,i);
        return start;
    }
    public static void swap(int[]arr,int left,int right){
        int tem=arr[left];
        arr[left]=arr[right];
        arr[right]=tem;
    }
    //归并
    public static void mergesort(int[]arr,int left,int right){
        if(left==right){
            return;
        }
        int mid=(left+right)/2;
        mergesort(arr,left,mid);
        mergesort(arr,mid+1,right);
        merge(arr,left,right,mid);
    }
    public static void merge(int[]arr,int left,int right,int mid){
        int s1=left;
        int e1=mid;
        int s2=mid+1;
        int e2=right;
        int k=0;//记录数组下标
        int temarr[]=new int[right-left+1];
        while(s1<e1&&s2<e2){
            if(arr[s1]<arr[s2]){
                temarr[k++]=arr[s1++];
            }
            else{
                temarr[k++]=arr[s2++];
            }
        }
        while(s1<e1){
            temarr[k++]=arr[s1++];
        }
        while(s2<e2){
            temarr[k++]=arr[s2++];
        }
        for(int i=0;i<temarr.length;i++){
            arr[left+i]=temarr[i];
        }
    }


}
